package com.heima.common.util;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author DJC
 */
public class OcrUtil {
    private final static String DATA_PATH = "D:\\Develop\\IdeaProjects\\tt\\heima-leadnews\\heima-leadnews-common\\src\\main\\java\\com\\heima\\common\\tessdata";
    private final static String LANGUAGE = "chi_sim";

    public static String doOcr(BufferedImage image) throws TesseractException {
        //创建Tesseract对象
        ITesseract tesseract = new Tesseract();
        //设置字体库路径
        tesseract.setDatapath(DATA_PATH);
        //中文识别
        tesseract.setLanguage(LANGUAGE);
        //执行ocr识别
        String result = tesseract.doOCR(image);
        //替换回车和tal键  使结果为一行
        result = result.replaceAll("[\\r\\n]", "-").replaceAll(" ", "");
        return result;
    }

    public static String ocrCheck(List<byte[]> byteList) throws TesseractException, IOException {

        //创建Tesseract对象
        ITesseract tesseract = new Tesseract();
        //设置字体库路径
        tesseract.setDatapath(DATA_PATH);
        //中文识别
        tesseract.setLanguage(LANGUAGE);

        String result = "";

        for (byte[] bytes : byteList) {
            ByteArrayInputStream image = new ByteArrayInputStream(bytes);
            BufferedImage read = ImageIO.read(image);
            //执行ocr识别
            String s = tesseract.doOCR(read);
            //替换回车和tal键  使结果为一行
            result += s.replaceAll("[\\r\\n]", "-").replaceAll(" ", "");
        }
        return result;

    }
}
